package com.renhong.springbootshiro.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.renhong.springbootshiro.service.UserService;

@Controller
public class UserController {
	
	/* 测试方法 */
	@RequiresPermissions("generator:goods:list")
	@RequestMapping("/hello")
	@ResponseBody
	public String hello() {
		System.out.println("1234");
		return "ok";
	}

	/* 测试 thymeleaf */
	@RequestMapping("/testThymeleaf")
	public String testThymeleaf(Model model) {
		model.addAttribute("name", "黑马程序员");
		// 返回test.html
		return "test";
	}

	@RequestMapping("/add")
	public String add(Model model) {
		return "user/add";
	}

	@RequestMapping("/update")
	public String update(Model model) {
		return "user/update";
	}

	@RequestMapping("/noAuth")
	public String noAuth(Model model) {
		model.addAttribute("msg", "你未经授权，无法访问该页面");
		return "noAuth";
	}
	
	@RequestMapping("/toLogin")
	public String toLogin(Model model) {
		return "login";
	}

	@RequestMapping("/login")
	public String login(String name, String password,Model model) {
		/*
		 * 使用shiro编写认证操作
		 */
		// 1.获取Subject
		Subject subject = SecurityUtils.getSubject();
		// 2.封装用户数据
		UsernamePasswordToken token = new UsernamePasswordToken(name, password);
		// 3.执行登录方法
		try {
			subject.login(token);
			// 登录成功
			return "redirect:testThymeleaf";
		} catch (UnknownAccountException e) {
			// 登录失败:用户名不存在
			model.addAttribute("msg", "用户名不存在");
			System.out.println("用户名不存在");
			return "login";
		}catch (IncorrectCredentialsException e) {
			// 登录失败:密码错误
			model.addAttribute("msg", "密码错误");
			System.out.println( "密码错误");
			return "login";
		}catch (Exception e) {
			// 登录失败:密码错误
			model.addAttribute("msg", "错误");
			return "login";
		}
	}
}
